% 定义输入和输出路径
imgFolderPath = 'data/img';
matFolderPath = 'data/mat';

% 创建输出目录（如果不存在）
if ~isfolder(matFolderPath)
    mkdir(matFolderPath);
end

% 获取目录中所有的 .img 文件
imgFiles = dir(fullfile(imgFolderPath, '*.img'));

% 遍历每个 .img 文件
for k = 1:length(imgFiles)
    % 获取 .img 文件名
    imgFileName = imgFiles(k).name;
    
    % 提取基础名（不包括扩展名）
    [~, baseName, ~] = fileparts(imgFileName);
    
    % 构建完整的文件路径
    imgFilePath = fullfile(imgFolderPath, imgFileName);
    hdrFilePath = fullfile(imgFolderPath, [baseName '.hdr']);  % 确保 .hdr 文件路径正确
    
    % 打印路径以进行调试
    % disp(['imgFileName: ', imgFileName]);
    % disp(['baseName: ', baseName]);
    % disp(['imgFilePath: ', imgFilePath]);
    % disp(['hdrFilePath: ', hdrFilePath]);
    
    % 检查 .hdr 文件是否存在
    if ~exist(hdrFilePath, 'file')
        warning('Header file not found: %s', hdrFilePath);
        continue;
    end
    
    % 读取 .hdr 文件内容
    fid = fopen(hdrFilePath, 'r');
    if fid == -1
        error('未能打开hdr文件');
    end

    headerLines = textscan(fid, '%s', 'Delimiter', '\n');
    fclose(fid);
    headerLines = headerLines{1};
    
    % 解析 .hdr 文件内容
    header = struct();
    for i = 1:length(headerLines)
        line = headerLines{i};
        if contains(line, '=')
            parts = strsplit(line, '=');
            key = strip(parts{1});
            value = strip(parts{2});
            
            % 打印键值对以进行调试
            disp(['Key: ', key, ', Value: ', value]);
            
            % 清理字段名称，去除空格和其他特殊字符
            cleanKey = regexprep(key, '[^a-zA-Z0-9_]', '_');
            
            % 检查值是否为缺失值
            if isempty(value) || strcmp(value, 'missing') || isnan(str2double(value))
                value = '';  % 设置默认值为空字符串
            end
            
            % 去掉小数点后的多余零
            if isnumeric(str2double(value))
                value = strtrim(num2str(str2double(value)));
            end
            
            try
                header.(cleanKey) = str2double(value);
            catch
                header.(cleanKey) = value;
            end
        end
    end
    
    % 提取必要的元数据
    samples = header.samples;
    lines = header.lines;
    bands = header.bands;
    dataType = header.data_type;  % 修改这一行
    
    % 确保 interleave 是字符串
    interleave = header.interleave;
    if ischar(interleave)
        interleave = lower(strip(interleave));
    else
        interleave = lower(string(interleave));
    end

    
    % 转换数据类型  
    switch dataType
        case 1
            precision = uint8(0);
            precisionStr = 'uint8';
        case 2
            precision = int16(0);
            precisionStr = 'int16';
        case 12
            precision = uint16(0);
            precisionStr = 'uint16';
        case 3
            precision = int32(0);
            precisionStr = 'int32';
        case 13
            precision = uint32(0);
            precisionStr = 'uint32';
        case 4
            precision = single(0);
            precisionStr = 'float32';
        case 5
            precision = double(0);
            precisionStr = 'double';
        otherwise
            error('Invalid data type in header file.');
    end
    % 计算数据类型的字节大小
    bytesPerElement = numel(typecast(precision, 'uint8'));
    % 读取 .img 文件内容
    imgData = zeros(lines,samples,bands,'like',precision);
        for b=1:bands
            offset = (b-1) * lines * samples * bytesPerElement;
            fid = fopen(imgFileName, 'r');  
            fseek(fid, offset, 'bof');  
            imgData(:, :, b) = fread(fid, [lines, samples], precisionStr);  
            fclose(fid);  
        end

        % 显示图像数据的一些基本信息
        disp(['Processing ', imgFileName, '...']);
        disp(['Image Data Dimensions: ', num2str(size(imgData))]);
        
        % 构建输出文件路径
        matFilePath = fullfile(matFolderPath, [baseName '.mat']);
        
        % 保存为 .mat 文件
        save(matFilePath, 'imgData');
        disp(['Saved to ', matFilePath]);
end